#include <QApplication>
#include <QIcon>
#include <QtConcurrent>
#include <QFutureWatcher>

#include "devicelistdialog.h"
#include "deviceuiwidget.h"

#include "adb/adbprocess.h"

QVariantList GetDeviceInfoList()
{
    QVariantList deviceList;
    QStringList devices = AdbProcess::GetDeviceList();
    if (devices.isEmpty())
    {
        return deviceList;
    }

    for (const QString &deviceId : qAsConst(devices))
    {
        QString brand = AdbProcess::GetBrand(deviceId);
        QString model = AdbProcess::GetModel(deviceId);
        QString name = AdbProcess::GetName(deviceId);

        QVariantMap info;
        info.insert("sn", deviceId);
        info.insert("brand", brand);
        info.insert("model", model);
        info.insert("name", name);
        deviceList << info;
    }
    if (deviceList.isEmpty())
    {
        return deviceList;
    }
    return deviceList;
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    // 设置全局字体
    QFont font("微软雅黑", 10);
    app.setFont(font);

    // 设置icon
    app.setWindowIcon(QIcon(":/images/logo.png"));

    QFuture<QVariantList> future = QtConcurrent::run(GetDeviceInfoList);
    QFutureWatcher<QVariantList> watcher;
    watcher.setFuture(future);
    QObject::connect(&watcher, &QFutureWatcher<QVariantList>::finished, [&]
    {
        QVariantList deviceList = future.result();
        if (deviceList.isEmpty())
        {
            app.quit();
            return;
        }
        QVariantMap selectedDevice;
        if (deviceList.count() == 1)
        {
            // 如果只有一个，就用这个设备
            selectedDevice = deviceList[0].toMap();
        }
        else
        {
            // 如果有多个设备，需要提示选择
            DeviceListDialog dialog;
            dialog.setDeviceList(deviceList);
            if (dialog.exec() != QDialog::Accepted)
            {
                app.quit();
                return;
            }
            selectedDevice = dialog.selectedDevice();
        }
        if (selectedDevice.isEmpty())
        {
            app.quit();
            return;
        }
        DeviceUiWidget *ui = new DeviceUiWidget;
        ui->setDeviceInfo(selectedDevice);
        ui->show();
    });
    return app.exec();
}
